import { AudioClip, AudioSource, director, Node } from "cc";

/**
 * 音频管理器
 */
export class AudioManager {

    private static _ins: AudioManager = null;

    /**AudioSource挂在在此节点上 */
    private m_AttachNode: Node = null;
    /**AudioSource组件 */
    private m_AudioSource: AudioSource = null;

    static get ins(): AudioManager {
        if (this._ins === null) {
            this._ins = new AudioManager();
        }
        return this._ins;
    }

    private constructor() {
        //私有化的构造函数
        // this.m_AttachNode = new Node("Sound_bg");
        // director.addPersistRootNode(this.m_AttachNode);
        this.m_AttachNode = director.getScene().getChildByName("Canvas");
        this.m_AudioSource = this.m_AttachNode.addComponent(AudioSource);
    }

    /**
     * 默认播放背景音乐接口
     * @param bUrl bundleName:子包名 url：资源路径
     */
    public async playBgMusic(bUrl: IBundleUrl) {
        //加载背景音乐后播放
        const audioClip = await gCtrl.res.loadAssetAsync(bUrl, AudioClip);
        let audioSource = this.m_AudioSource;
        audioSource.clip = audioClip;
        audioSource.loop = true;
        audioSource.play();
    }
}